/* eslint-disable no-underscore-dangle */
import React, { useEffect, useState } from 'react';
import {
  Page, Header, HeaderButtons, Breadcrumb, Content,
  continuousDeploymentApi,
} from '@choerodon/master';
import { Icon, message } from 'choerodon-ui/pro';
import { useParams, useHistory, useLocation } from 'react-router';
import { Modal } from '@choerodon/master/lib/components/modal';
import { inject } from 'mobx-react';
import { observer } from 'mobx-react-lite';
// @ts-ignore
import queryString from 'query-string';
import { omit } from 'lodash';
import uuidV1 from 'uuid';
import StagesEdits from '@/routes/app-pipeline/routes/app-pipeline-edit/components/stage-edits';
import { useStore } from './stores';
import BasicConfigurationForm from './components/basic-configuration-form';
import { defaultStageData, defaultBasicConfigurationData } from './CONSTANTS';
import {
  transformBasicConfDataToSubmit, transformBasicConfDataToUse,
  validateStageData, validateBasicConfigurationData,
} from './utils';
import BasicConfigurationCard from '@/routes/continuous-deployment/components/basicConfigurationCard';
import { getTriggerAddress, getcurlText } from '../../utils';
import './index.less';

export interface IProps {

}

const modalkey1 = Modal.key();
export type TAction = 'create' | 'edit'

const PageContent: React.FC<IProps> = (props) => {
  // @ts-ignore
  const { AppState: { currentMenuType: { projectId } } } = props;
  const {
    intlPrefix, prefixCls,
  } = useStore();

  const [stageData, setStageData] = useState<any>([]);
  const [basicConfigurationData, setBasicConfigurationData] = useState<any>({});

  const params = useParams<any>();
  const { type }: { type: TAction } = params;
  const history = useHistory();
  const { search } = useLocation();
  const { pipelineId, personalToken } = queryString.parse(search);

  const triggerAddress = getTriggerAddress(projectId);
  const curlText = getcurlText(basicConfigurationData.token, personalToken, projectId);

  useEffect(() => {
    async function asyncFunc() {
      if (type === 'create') {
        setStageData(defaultStageData);
        setBasicConfigurationData({
          ...defaultBasicConfigurationData,
          token: uuidV1(),
        });
      } else {
        const res = await continuousDeploymentApi.getDeploymentProcessDetail(pipelineId);
        setBasicConfigurationData(transformBasicConfDataToUse(res));
        setStageData(res.stageList);
      }
    }
    asyncFunc();
  }, []);

  const handleSubmit = async () => {
    let searchObj = queryString.parse(search);
    searchObj = omit(searchObj, ['personalToken', 'pipelineId']);
    const str = queryString.stringify(searchObj);

    const ValidateBasicConfigurationDataRes = validateBasicConfigurationData(
      basicConfigurationData,
    );
    const validateStageRes = validateStageData(stageData);

    if (ValidateBasicConfigurationDataRes) {
      message.error(ValidateBasicConfigurationDataRes);
      return;
    }

    if (validateStageRes) {
      message.error(validateStageRes);
      return;
    }

    const postData = {
      ...transformBasicConfDataToSubmit(basicConfigurationData),
      projectId,
      stageList: stageData,
    };

    type === 'create'
      ? await continuousDeploymentApi.createDeploymentProcess(postData)
      : await continuousDeploymentApi.editDeploymentProcess(pipelineId, postData);

    try {
      message.success(type === 'create' ? '创建成功' : '修改成功');
      setTimeout(() => {
        history.push({
          pathname: '/devops/continuous-deployment',
          search: `?${str}`,
        });
      }, 1000);
    } catch (error) {
      console.log(error);
    }
  };

  const handleCancel = () => {
    history.go(-1);
  };

  const headerBtns = () => [
    {
      name: '保存',
      icon: 'check',
      handler: () => { handleSubmit(); },
    },
    {
      name: '取消',
      icon: 'close',
      handler: () => { handleCancel(); }, // 回到列表页,
    },
  ];

  const handleBasicConfigurationModalOk = (BasicConfFormData: any) => {
    setBasicConfigurationData(BasicConfFormData);
    console.log(BasicConfFormData, 'BasicConfFormData');
  };

  const handleOpenBasicConfigurationModal = () => {
    Modal.open({
      title: '基础配置',
      key: modalkey1,
      drawer: true,
      maskClosable: false,
      style: {
        width: 650,
      },
      children: (
        <BasicConfigurationForm
          formData={basicConfigurationData}
          pipelineId={pipelineId}
          projectId={projectId}
          curlText={curlText}
          triggerAddress={triggerAddress}
          personalToken={personalToken}
          onModalOk={handleBasicConfigurationModalOk}
          type={type}
        />
      ),
      okText: '保存',
    });
  };

  return (
    <>
      <Page service={[]}>
        <Header>
          <HeaderButtons items={headerBtns()} />
        </Header>
        <Breadcrumb title={type === 'create' ? '创建部署流程' : '修改部署流程'} />
        <Content className={prefixCls}>
          <div className={`${prefixCls}-stages`}>
            <div className={`${prefixCls}-stages-basic-configuration`} role="none" onClick={handleOpenBasicConfigurationModal}>
              <div className={`${prefixCls}-stages-basic-configuration-stage`}>
                <header>
                  <Icon type="tune" />
                  <span>基础配置</span>
                </header>
                {
                  Object.keys(basicConfigurationData).length ? (
                    <BasicConfigurationCard
                      basicConfigurationData={basicConfigurationData}
                      personalToken={personalToken}
                    />
                  ) : ''
                }
              </div>
              <div className={`${prefixCls}-stages-basic-configuration-line`} />
            </div>
            <StagesEdits
              isContinuousDeployment
              customState={stageData}
              customStateAction={setStageData}
            />
          </div>
        </Content>
      </Page>
    </>
  );
};

export default inject('AppState')(observer(PageContent));
